package com.zhangxi.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zhangxi.constant.MessageConstant;
import com.zhangxi.constant.PasswordConstant;
import com.zhangxi.constant.StatusConstant;
import com.zhangxi.context.BaseContext;
import com.zhangxi.dto.EmployeeDTO;
import com.zhangxi.dto.EmployeeEditPasswordDTO;
import com.zhangxi.dto.EmployeeLoginDTO;
import com.zhangxi.dto.EmployeePageQueryDTO;
import com.zhangxi.entity.Employee;
import com.zhangxi.exception.AccountLockedException;
import com.zhangxi.exception.AccountNotFoundException;
import com.zhangxi.exception.PasswordErrorException;
import com.zhangxi.mapper.EmployeeMapper;
import com.zhangxi.result.PageResult;
import com.zhangxi.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author zhangxi
 * @create 2024-04-17 20:36
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    @Override
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String name = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();
        //根据用户名查询员工信息
        Employee employee = employeeMapper.getByUsername(name);
        //处理各种异常情况
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //密码比对
        //MD5解密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }
        //通过上面的校验即可成功返回员工信息
        return employee;
    }

    /**
     * 员工新增
     *
     * @param employeeDTO
     */
    @Override
    public void save(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        //对象属性拷贝
        BeanUtils.copyProperties(employeeDTO, employee);
        //设置账号的默认状态
        employee.setStatus(StatusConstant.ENABLE);
        //设置密码,使用MD5加密
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        //设置当前记录的创建时间和更新时间
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
        //设置当前记录创建人的ID
//        employee.setCreateUser(10L); //后期修改逻辑
//        employee.setUpdateUser(10L);//后期修改逻辑
//        employee.setCreateUser(BaseContext.getCurrentId());
//        employee.setUpdateUser(BaseContext.getCurrentId());
//        已增加aspect做自动赋值操作
//        执行insert操作
        employeeMapper.insert(employee);
    }

    @Override
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        //开始分页查询
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        //执行查询操作
        Page<Employee> page = employeeMapper.pageQuery(employeePageQueryDTO);
        //获取总记录数
        long total = page.getTotal();
        List<Employee> employees = page.getResult();
        //返回封装好的结果
        return new PageResult(total, employees);
    }

    /**
     * 启用或者禁用员工账号
     *
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        //使用构建者模式构建一个employee
        Employee employee = Employee.builder()
                .status(status)
                .id(id)
                .build();
        employeeMapper.update(employee);
    }

    /**
     * 根据Id查询员工信息
     *
     * @param id
     * @return
     */
    @Override
    public Employee getById(Long id) {
        Employee employee = employeeMapper.getById(id);
        //设置密码为不可显示
        employee.setPassword("******");
        return employee;
    }

    /**
     * 修改员工信息
     *
     * @param employeeDTO
     */
    @Override
    public void update(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        //对象属性拷贝
        BeanUtils.copyProperties(employeeDTO, employee);
        //设置更新人和更新时间
//        employee.setUpdateUser(BaseContext.getCurrentId());
//        employee.setUpdateTime(LocalDateTime.now());
// 已增加Aspect公共字段填充处理
        employeeMapper.update(employee);
    }

    /**
     * 修改密码操作
     *
     * @param employeeEditPasswordDTO
     */

    @Override
    public void editPassword(EmployeeEditPasswordDTO employeeEditPasswordDTO) {
        String newPassword = employeeEditPasswordDTO.getNewPassword();
        String oldPassowrd = employeeEditPasswordDTO.getOldPassword();
        Long id = BaseContext.getCurrentId();
        //根据id查询Employee
        Employee employee = employeeMapper.getById(id);
        //处理各种异常情况
        //查看旧密码是否一样
        if (!DigestUtils.md5DigestAsHex(oldPassowrd.getBytes()).equals(employee.getPassword())) {
            throw new PasswordErrorException(MessageConstant.PASSWORD_EDIT_FAILED);
        }
        employee.setPassword(DigestUtils.md5DigestAsHex(newPassword.getBytes()));
        employee.setUpdateTime(LocalDateTime.now());
        //执行更新操作
        employeeMapper.update(employee);
    }
}
